<template>
  <!-- 专家评审-->
  <div class="container">
    <el-row class="">
      <el-col :span="16" align="left">
        <el-input v-model="data.params.projectName" placeholder="项目名称" style="width: 150px; margin-right: 15px" />
        <el-button color="#626aef" @click="search()" class="ordinary">搜索</el-button>
      </el-col>

      <el-col :span="8" align="right">
<!--        <el-button class="ordinary" @click="getExport()" v-limit="'XMZX:SZXMLXPS:ZJPS:EXPORT'">批量导出</el-button>-->
        <el-button class="ordinary" @click="handleExport()" v-limit="'XMZX:SZXMLXPS:ZJPS:EXPORT'"> 批量导出</el-button>
        <el-button type="danger" @click="handleDetect()" v-limit="'XMZX:SZXMLXPS:ZJPS:SETUPREVEX'">设置评审专家</el-button>
        <el-button type="primary" @click="handleAdd()" v-limit="'XMZX:SZXMLXPS:ZJPS:REVCONFIRM'">评审确认</el-button>
        <el-button class="lock" @click="openExpert()" v-limit="'XMZX:SZXMLXPS:ZJPS:EXREV'">专家评审</el-button>
      </el-col>
    </el-row>

    <div class="banner">
      <!-- 列表单选表格 -->
      <el-table :data="data.allTableData" style="width: 100%" class="center-table"    @row-dblclick="handleRowClick" >
        <el-table-column width="55" align="center" prop="checked" label="选择">
          <template #default="{row,$index}">
            <el-checkbox v-model="row.checked" @change="selectTable( $event, row , $index)" ></el-checkbox>
          </template>
        </el-table-column>

        <el-table-column type="index" :index="indexMethod" label="序号" width="50" />
        <ColumnData v-for="column of data.columns" :key="column.label" :item="column" />
        <el-table-column  label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <el-button size="small" class="ordinary" @click="handleEdit(row)" v-limit="'XMZX:SZXMLXPS:ZJPS:DETAILS'">详情</el-button>
            <el-button size="small" class="ordinary" @click="openResult(row)" v-limit="'XMZX:SZXMLXPS:ZJPS:DETAILS'">查看专家初审结果</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="example-pagination-block">
            <el-pagination
              :current-page="data.params.current"
              :page-size="data.params.size"
              :page-sizes="[10, 20, 30, 40,50,100]"
              background
              layout="prev, pager, next ,total,sizes,jumper"
              :total="data.page.total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"/>
      </div>
    </div>
    <!--  -----------------------   设置专家评审 --------------------  -->
    <el-dialog class="setUpExperts" v-model="data.setUpExpertsDialog" width="80%" :show-close="false" @closed="handleCloseDialog" title="设置专家评审">
      <template #title>
        <SetUpExpertsDialog v-if="data.setUpExpertsDialog" :initSelection="data.initSelection" @delectIdsSetUp="delectIdsSetUp"/>
      </template>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.setUpExpertsDialog = false">关闭</el-button>
          <el-button type="primary" @click="addSetUpExperts()">设置选中专家</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- -----------------------     评审确认-->
    <el-dialog v-model="data.reviewConfirmation" width="60%" :show-close="true" title="专家评审结果" >
      <template #title>
        <el-form :model="data.reviewForm" :rules="rules" ref="ruleFormRef" status-icon label-position="right" label-width="120px"
          :inline="true" class="demo-form-inline">
          <el-form-item label="专家评分" style="width: 100%">
            <el-table
              :data="data.tableDataCast"
              border>
              <el-table-column prop="projectName" label="项目名称"></el-table-column>
              <el-table-column prop="expertNumber" label="专家数量"></el-table-column>
              <el-table-column prop="isNum" label="同意票数"></el-table-column>
              <el-table-column prop="isNotNum" label="不同意票数"></el-table-column>
            </el-table>
          </el-form-item>
          <el-form-item label="审批意见" style="width: 100%" prop="opinion">
            <el-input v-model="data.reviewForm.opinion" :autosize="{ minRows: 3 }"  maxlength="512"  show-word-limit  type="textarea" placeholder="请输入" />
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <span class="dialog1-footer" style="text-align: center;">
          <el-button type="primary"  @click="noPass('5')">评审通过</el-button>
          <el-button @click="noPass('3')">评审不通过</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- ----------------------      专家审批-->
    <el-dialog v-model="data.openExpert"  :rules="rules"  width="60%" :show-close="true" title="专家评审结果" style="min-height: 200px;" @closed="data.reviewForm.expertOpinion = ''">
      <template #title >
        <div class="box" style="height: 400px;">
          <span>评审意见：</span>
<!--          <el-form-item label="审批意见" style="width: 100%">-->
          <el-input v-model="data.reviewForm.expertOpinion" :autosize="{ minRows: 15 }"  maxlength="512"  show-word-limit type="textarea" placeholder="请输入" />

        </div>
      </template>
      <template #footer>
        <span style="text-align: center;">
          <el-button type="primary"  @click="expertPass('1')">通过</el-button>
          <el-button @click="expertPass('2')">不通过</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- -------------------------查看专家初审结果 -->
    <el-dialog v-model="data.openResult" width="60%" :show-close="true" style="min-height: 200px;">
      <template #title>
        <resultDialog :lookId="data.lookId" v-if="data.openResult"/>
      </template>
      <template #footer>
        <span style="text-align: center;">
          <el-button @click="data.openResult = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- -------------------------详情 -->
    <el-dialog v-model="data.openDetail" width="60%" :show-close="true" style="min-height: 200px;">
      <template #title>
        <div class="my-header" >
          <el-tabs v-model="activeName" class="demo-tabs">
            <el-tab-pane label="基本信息" name="1">
              <detailDialog :detailData="data.detailData" :lookId="data.lookId"/>
            </el-tab-pane>
            <el-tab-pane label="项目经费预算" name="2">
              <el-table :data="data.tableBudget" border>
                <el-table-column type="index" label="序号" width="50" />
                <el-table-column prop="costCategoryName" label="费用分类"></el-table-column>
                <el-table-column prop="subjectName" label="科目名称"></el-table-column>
                <el-table-column prop="amount" label="金额(万元)"></el-table-column>
                <el-table-column prop="remark" label="备注"></el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </div>

      </template>
      <template #footer>
        <span style="text-align: center;">
          <el-button @click="data.openDetail = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>


    <!-- 导出字段选择 -->
    <Export
        :detailList="data.detailList"
        :showing="data.exportDialog"
        @close="closeExport"
        @handle-filed="handleFiled"
    ></Export>
  </div>
</template>
<script lang="ts">
import Information from '@/views/project/digit/requirementApplication/information.vue'
import {
  addExpertReview,
  doApprove,
  getExpertReview,
  getExportExpertReview,
  getExportExpertReview1,
  hadDetail,
  opinionApprove,
  votesCast
} from '@/views/science/api/digit'
import Members from '@/views/science/components/members/members.vue'
import platformFiles from '@/views/science/components/platformFiles/platformFiles.vue'
import record from '@/views/science/components/record/record.vue'
import SelectOption from '@/views/science/components/selectOption/index.vue'
import ColumnData from '@/views/science/components/table/column-data.vue'
import Table from '@/views/science/components/table/table.vue'
import { Modals } from '@/views/science/components/tips/tips'
import {ElMessage, ElMessageBox} from "element-plus"
import { computed, reactive, ref } from 'vue'
import { useStore } from 'vuex'
import detailDialog from './components/detailDialog.vue'
import resultDialog from './components/resultDialog.vue'
import SetUpExpertsDialog from './components/setUpExpertsDialog.vue'
import tableData from './tableHeader.json'
import Export from '@/views/project/components/Export/index.vue'
import {getLxsqTeam1} from "@/views/project/api/szhlxsp";
import { servicesLoading } from '@/utils/loading'

export default {
  components: {
    SelectOption,
    Table,
    Information,
    Members,
    platformFiles,
    record,
    SetUpExpertsDialog,
    ColumnData,
    resultDialog,
    detailDialog,
    Export,
  },
  setup() {
    const store = useStore()
    const activeName = ref('1')
    const pagination = reactive({  //分页器信息
      pageSize:10,
      currentPage:1,
    })

    //分页操作
    const handleSizeChange = (val) =>{
      data.params.current = 1
      data.params.size = val
      tableList()
    }
    const handleCurrentChange = (val) =>{
      data.params.current = val
      tableList()
    }
    let data = reactive({
      detailId:'',
      dialogVisible: false,
      setUpExpertsDialog:false,
      initSelection:[],
      reviewConfirmation:false,//
      addFlag: 0,
      recordShow: false,
      loading: false,
      page: { page: 1, limit: 10, total: 4 },
      params: {
        projectName: "",
        current: 1,
        size: 10,
      },
      tableItem:{id:'',status:'',} as any,//当前选中的行
      selectedRows: [],
      columns: tableData.platformTableHeader,
      ids: [],
      allTableData: [],
      orgAllList: computed(() => store.state.technologyStrength.orgAllList),
      levelOptions: computed(() => store.state.innovativeTalents.cxlevelSelect),
      members: [],
      files: [],
      changeLogs: [],
      flag: null,

      baseInfo: [],
      memberList: [],
      fileList: [],

      setupIds:[],//设置专家评选的弹窗ids
      reviewForm:{//审批确认弹窗
        score:'',
        opinion:'',//意见
        expertOpinion:'',//专家审批按钮意见
      },
      tableDataCast:[],//投票票数表格

      // 专家审批
      openExpert:false,
      //查看专家初审结果
      openResult:false,
      lookId:'',//id
      //详情
      openDetail:false,
      detailData:{},
      tableBudget:[],//经费预算
      exportDialog: false,
      detailList: [] as any,
    });
    const closeExport = () => {
      data.exportDialog = false
    }
    const handleFiled = (arr) => {
      console.log(arr, 'handleFiled')
      // let sdt = data.tableItem.map((el) => el.id);
      if (arr.length > 0) {
        ElMessageBox.confirm('您确认导出查询数据吗？', '批量导出', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          getExportExpertReview1({ ...data.params, ids: [data.tableItem.id] , headList: arr }, '数字化专家评审')
          // getExportExpertReview1({ ...data.params, ids: data.tableItem.id , headList: arr}, "数字化专家评审");
          console.log('批量导出')
          data.exportDialog = false;
        })
      }else if (arr.length > 0){
        ElMessage.warning(`请选择一条要设置导出标头`)
      }

    }
    const handleExport = () => {
      data.exportDialog = true
      data.detailList = [
        { fieldName: 'projectName', title: '项目名称' },
        { fieldName: 'projectCategory', title: '项目类别' },
        { fieldName: 'projectStartTime', title: '项目开始时间' },
        { fieldName: 'projectEndTime', title: '预计完成时间' },
        // { fieldName: 'projectLeader', title: '项目负责人' },
        { fieldName: 'applyUnit', title: '申报单位' },
        // { fieldName: 'projectLeader', title: '项目负责人' },
        // { fieldName: 'contactPhone', title: '联系电话' },
        // { fieldName: 'completionPeriod', title: '完成年限' },
        { fieldName: 'totalBudget', title: '总投资(万元)' },
        // { fieldName: 'applyBudget', title: '申请中咨拨款(万元)' },
        { fieldName: 'applyDate', title: '申报日期' },
        { fieldName: 'summarize', title: '概述' },
        { fieldName: 'demandAnalysis', title: '现状及需求分析' },
        { fieldName: 'feasibilityNalysis', title: '项目必要性和可行性分析' },
        { fieldName: 'implementationPlan', title: '项目内容和实施方案' },
        { fieldName: 'projectSchedule', title: '项目进度计划' },
        { fieldName: 'projectCostEstimation', title: '项目费用估算' },
        { fieldName: 'projectBenefitAnalysis', title: '项目效益分析' },
        { fieldName: 'riskCountermeasure', title: '风险及对策' },
        { fieldName: 'stu', title: '状态' },
        /*          { fieldName: 'researchContent', title: '主要研究内容' },
                 { fieldName: 'economicIndicator', title: '主要技术经济指标' },
                 { fieldName: 'intellectualProperty', title: '创新点及可能获得的成果和知识产权' },
                 { fieldName: 'projectBackground', title: '立项背景(包括项目背景、项目概况、研究的必要性等)' },
                 { fieldName: 'feasibilityAnalysis', title: '国内外研究概况及可行性分析' },
                 { fieldName: 'technicalIndex', title: '项目研究的主要内容及技术指标' },
                 { fieldName: 'technicalRoute', title: '项目研究的技术路线' },
                 { fieldName: 'benefitForecast', title: '推广应用前景及经济效益预测' },
                 { fieldName: 'unitDivision', title: '申报单位和协作单位及分工' },
                 { fieldName: 'economicIndicator', title: '主要技术经济指标' },
                 { fieldName: 'intellectualProperty', title: '创新点及可能获得的成果和知识产权' },*/
      ]
    }
    interface Config {
      id: string;
      status: string;
    }
    let selectArr: Config[] = reactive([]);
    const handleSelectionChange = (val) => {
      selectArr = val;
    };

    //列表
    const tableList = async () => {
      let res = await getExpertReview(data.params)
      if (res.data.success) {
        let records = res.data.data
        records.records.map((item) => {
          switch(item.status){
              case 0:item.status = '草稿';break;
              case 1:item.status = '待提交';break;
              case 2:item.status = '待专家评审';break;
              case 3:item.status = '专家评审未通过';break;
              case 4:item.status = '领导班子会审不通过';break;
              case 5:item.status = '待领导班子会审';break;
              case 6:item.status = '待批准';break;
              case 7:item.status = '批准立项';break;
              case 8:item.status = '立项拒绝';break;
          }
        })
        //给数据添加checked属性并默认置为false
        for ( let index in records.records ){
          records.records[index].checked = false
        }

        data.allTableData = records.records
        data.page.total = records.total
      }
    }
    //单选
    const selectTable = (e,row,index) =>{
      const data1 = data.allTableData
      //遍历表格的数据，将非本行的所有数据的checked属性置为false，即取消选择
      for(let i in data1){
        if( i == index ){
            (data1[i] as any).checked = e
        }else{
            (data1[i] as any).checked = false
        }
      }
      data.allTableData = data1
      if(e){
        data.tableItem = row
      }else{
        data.tableItem = {id:''}
      }
      console.log('单选',data.tableItem);
    }
    //多选
    const selectdx = (e,row,index) =>{
      const data1 = data.allTableData

      data.allTableData = data1

        data.tableItem = row

      console.log('多选',data.tableItem);
    }
    const indexMethod = (index)=>{
      return data.params.size*(data.params.current-1) +index+1
    }
    const delectIds = (ids) => {
      data.ids = ids
    }

    //批量导出
    const getExport = async () => {
      Modals('是否导出全部数据', '提示', 'warning').then(async () => {
        await getExportExpertReview({projectName:data.params.projectName})
      }).catch(() => {
        console.log("点击了取消")
      })
    }

    //设置专家评审--------------------------------------------------
    const handleDetect = async () => {
      if(data.tableItem.status != '待专家评审'){
        ElMessage.warning(`待专家评审状态才能设置评审专家`)
        return;
      }
      // if(Object.keys(data.tableItem).length > 1){
      if(Object.keys(data.tableItem).length >= 1){
        const loading = servicesLoading({ fullscreen: true })
        hadDetail({id:data.tableItem.id}).then(res =>{
          console.log('详情',res.data.data.expertReviewList);
          data.initSelection = res.data.data.expertReviewList?.map(item=>{
            return item.expertId
          })
          data.setUpExpertsDialog = true
          loading.close()
        }).catch(()=>{
            loading.close()
          })
      }else{
        // ElMessage.warning(`请选择要设置的内容`)
        ElMessage.warning(`请选择一条要设置的内容`)
      }
    }
    //设置专家评审  弹窗内多选
    const delectIdsSetUp = (val) =>{
      data.setupIds = val
    }
    //设置选中专家
    const addSetUpExperts = async () => {
      data.setupIds.forEach((e) =>{
        Reflect.set(e, 'applicationId', data.tableItem.id)
      })
      addExpertReview(data.tableItem.id,data.setupIds).then(res =>{
        if(res.data.code == 200){
          ElMessage.success(`设置专家成功`)
          tableList()
        }
        data.tableItem = {id:''}
        data.setUpExpertsDialog = false
      })
    }

    // 点击查询按键，分页设置为当前页为1，
    const search = () => {
      data.page.page = 1
      tableList()
    }

    //-------------------------------评审确认--------------------------
    // 点击弹出
    const handleAdd = () => {
      console.log("审核",data.tableItem)
      // if(Object.keys(data.tableItem).length > 1){
      if(Object.keys(data.tableItem).length > 1){
          //判断部分状态 不可以进行这个操作
          if(data.tableItem.status == '待专家评审'){
            data.reviewConfirmation = true
            votesCast({id:data.tableItem.id}).then((res:any) =>{
              data.tableDataCast = res.data.data
            })
          }else{
            ElMessage.warning(`该数据已评审完成`)
          }
      }else{
        ElMessage.warning(`请选择一条要设置的内容`)
      }
    }
    const rules = reactive({
      projectName: [
        { required: true, message: '请输入项目名称', trigger: 'blur' },
      ],
      opinion: [
        { required: true, message: '请输入意见', trigger: 'blur' },
      ],
      expertOpinion: [
        { required: true, message: '请输入审批意见', trigger: 'blur' },
      ],
    })
    //通过  不通过
    const noPass = (val) =>{data.reviewForm.opinion
      if(data.reviewForm.opinion == ''){
        ElMessage.warning(`请输入审批意见内容`)
        return
      }
      let obj = {
        id:data.tableItem.id,
        expertReviewComments:data.reviewForm.opinion,
        expertFileName:'',//  专家评审附件名称
        expertFilePath:'',//  专家评审附件路径
        status:val,
      }
      doApprove([obj]).then(res =>{
        if(res.data.code == 200){
          ElMessage.success(`审批成功`)
          tableList()
        }
        data.tableItem = {id:''}
        data.reviewConfirmation = false
        data.reviewForm.opinion = ''
      })
    }
    //------------------------专家审批按钮
    //专家评申 弹出弹框
    const openExpert = async () => {
      // if(Object.keys(data.tableItem).length > 1){
      if(Object.keys(data.tableItem).length > 1){
        //判断部分状态 不可以进行这个操作
        if(data.tableItem.status == '待专家评审'){
           data.openExpert = true
          }else{
            ElMessage.warning(`该数据已评审完成`)
          }

      }else{
        ElMessage.warning(`请选择一条要设置的内容`)
      }
    }
    const expertPass = (val) =>{
      if(data.reviewForm.expertOpinion == ''){
        ElMessage.warning(`请输入评审意见内容`)
        return
      }
      let obj = {
        applicationId:data.tableItem.id,
        expertOpinion:data.reviewForm.expertOpinion,
        conclusion:val,
      }
      opinionApprove([obj]).then(res =>{
        if(res.data.code == 200){
          ElMessage.success(`审批成功`)
          tableList()
        }
        data.tableItem = {id:''}
        data.openExpert = false
      })
    }

    //-------------------------查看专家初审结果
    const openResult = (val) =>{
      data.lookId = val.id
      data.openResult = true
      console.log('data.lookId',data.lookId);
    }
    const handleRowClick = (row) => {
      handleEdit(row)
    }
    //-------------------------详情
    const handleEdit = (row) => {
      // data.detailId = row.id
      hadDetail({id:row.id}).then(res =>{
        // console.log('详情',res);
        const config = { ...res.data.data.info };
        config.approvalFilePath = config.approvalFilePath ? JSON.parse(config.approvalFilePath) : [];
        data.detailData = config;
        data.tableBudget = res.data.data.contractBudgetList;
      })
      data.openDetail = true
      // store.commit('innovativeTalents/getRowId', row.id)
    }

    const handleCloseDialog = () => {
      // data.dialogVisible = false;
      data.recordShow = false;
      activeName.value = '1'
    }

    tableList()

    return {
      pagination,
      handleSizeChange,
      handleCurrentChange,
      data,
      activeName,
      indexMethod,
      delectIds,
      openExpert,
      openResult,
      getExport,
      handleDetect,
      handleAdd,
      handleCloseDialog,

      handleEdit,
      search,
      addSetUpExperts,
      delectIdsSetUp,
      rules,
      selectTable,
      noPass,
      expertPass,

      selectdx,

      closeExport,
      handleFiled,
      handleExport,
      handleRowClick,
    }
  },
}
</script>

<style lang="scss">
.table_{
  .el-pagination {
      display: none;
    }
}
</style>
<style lang="scss" scoped>
.example-pagination-block {
  margin-top: 15px;
  text-align: center;
}

:deep(.el-pagination .btn-next .el-icon) {
  margin: 0 auto;
}

:deep(.el-pagination .btn-prev .el-icon) {
  margin: 0 auto;
}
.container {
  background-color: white;
  padding: 20px;
}

:deep(.el-dialog__body) {
  display: none;
}

// .el-col {
//   line-height: 40px;
// }

.el-form-item {
  .el-input {
    width: 100px;
  }

  .el-select {
    width: 100px;
  }
}

/* .demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
} */
:deep(.center-table td),
:deep(.center-table th) {
  text-align: center !important;
}
:deep(.center-table) {
  margin-top: 15px;
}
.box{
  display: flex;
  align-content: center;
  justify-content: center;
  padding-top: 40px;
  span{
    width: 100px;
    text-align: center;
    line-height: 35px;
  }
}
</style>
